import 'dart:async';
import 'dart:convert';
import 'dart:typed_data';

import 'package:chop/Model/order_entity.dart';
import 'package:chop/Model/order_img_entity.dart';
import 'package:chop/common/DioUtils.dart';
import 'package:chop/common/MessageUtils.dart';
import 'package:chop/common/SPUtils.dart';
import 'package:chop/common/StringUtils.dart';
import 'package:chop/common/configs.dart';
import 'package:chop/view/Driver/riderOrderItem.dart';
import 'package:chop/view/Driver/uploadImg.dart';
import 'package:chop/widgets/TextSizeWidget.dart';
import 'package:chop/widgets/ToastWidget.dart';
import 'package:chop/widgets/appBar.dart';
import 'package:chop/widgets/behavior.dart';
import 'package:chop/widgets/loadingDialog.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:google_map_polyline/google_map_polyline.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'package:loading_animations/loading_animations.dart';
import 'dart:ui' as ui;
import 'package:chop/view/home/place_an_order/Delivery_order.dart';
import 'dart:io';

//正在进行订单
class RiderOrderInfo extends StatefulWidget {
  final String uuid;

  const RiderOrderInfo({Key key, this.uuid}) : super(key: key);

  @override
  _OrdedrUnfinishedState createState() => _OrdedrUnfinishedState();
}

class _OrdedrUnfinishedState extends State<RiderOrderInfo> {
  // 是否在网络请求中
  bool isNetworkNotBad = false;
  var _imgPath;

  // 订单id
  String uuid;

  // 当前位置
  Position nowPosition;

  // 订单信息
  orderData data;
  List<OrderInfo> infos = [];
  List<OrderImg> imgs = [];
  GoogleMapPolyline googleMapPolyline =
      GoogleMapPolyline(apiKey: Configs.API_KEY);

  // 地图标记
  Set<Marker> Markers = Set();

  // 地图控制器
  Completer<GoogleMapController> _controller = Completer();

  Widget getBody() {
    if (isNetworkNotBad) {
      print("加载完成");
      if(infos.length == 3){
        return getInfo(data);
      }else{
        return _buildBody();
      }
    } else {
      print("正在加载");
      return Center(child: LoadingJumpingLine.square());
    }
  }

  Widget _buildBody() {
    return Container(
      child: Stack(
        children: <Widget>[
          GoogleMap(
            initialCameraPosition: CameraPosition(
              target: LatLng(
                  double.parse(data.beginLat), double.parse(data.beginLng)),
              zoom: 14.4746,
            ),
            polylines: Set<Polyline>.of(_polylines.values),
            markers: Markers,
            onMapCreated: (GoogleMapController controller) {
              _controller.complete(controller);
            },
          ),
          Positioned(
              bottom: 10,
              height: 300,
              width: MediaQuery.of(context).size.width,
              child: ScrollConfiguration(
                behavior: MyBehavior(),
                child: ListView(
                  children: <Widget>[
                    Container(
                      height: 10,
                    ),
                    getColumn("订单信息",
                        child: Column(
                          children: <Widget>[
                            Container(
                              padding: EdgeInsets.fromLTRB(15, 5, 15, 0),
                              child: Row(
                                children: <Widget>[
                                  Expanded(
                                    child: Column(
                                      children: <Widget>[
                                        Row(
                                          children: <Widget>[
                                            Container(
//                        width: double.infinity,
                                              padding: EdgeInsets.only(
                                                  top: 5, bottom: 5),
                                              child: FixedSizeText(
                                                "订单号：${data.uuid}",
                                                textAlign: TextAlign.start,
                                                style: TextStyle(
                                                    fontSize: 16,
                                                    fontWeight:
                                                        FontWeight.bold),
                                              ),
                                            )
                                          ],
                                        ),
                                        Row(
                                          children: <Widget>[
                                            Container(
//                        width: double.infinity,
                                              padding: EdgeInsets.only(
                                                  top: 5, bottom: 5),
                                              child: FixedSizeText(
                                                "订单状态：${getStatus(data.status)}",
                                                textAlign: TextAlign.start,
                                                style: TextStyle(
                                                  fontSize: 16,
                                                ),
                                              ),
                                            )
                                          ],
                                        ),
                                        Container(
                                          padding: EdgeInsets.only(
                                              top: 5, bottom: 5),
                                          child: Row(
                                            children: <Widget>[
                                              Icon(
                                                Icons.subdirectory_arrow_right,
                                                size: 15,
                                                color: Colors.greenAccent,
                                              ),
                                              Container(
                                                width: 5,
                                              ),
                                              Expanded(
                                                child: FixedSizeText(
                                                  "${data.begin}",
                                                  textAlign: TextAlign.left,
                                                  maxLines: 4,
//                        overflow: TextOverflow.ellipsis,
                                                  style: TextStyle(),
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                        Container(
                                          padding: EdgeInsets.only(
                                              top: 5, bottom: 5),
                                          child: Row(
                                            children: <Widget>[
                                              Icon(
                                                Icons.subdirectory_arrow_left,
                                                size: 15,
                                                color: Colors.redAccent,
                                              ),
                                              Container(
                                                width: 5,
                                              ),
                                              Expanded(
                                                child: FixedSizeText(
                                                  "${data.end}",
                                                  textAlign: TextAlign.left,
                                                  overflow:
                                                      TextOverflow.ellipsis,
                                                  style: TextStyle(),
                                                ),
                                              )
                                            ],
                                          ),
                                        ),
                                        Row(
                                          children: <Widget>[
                                            Expanded(
                                              child: Container(
                                                child: FixedSizeText(
                                                  "路程",
                                                  style: TextStyle(
                                                      color: Colors.black45),
                                                ),
                                              ),
                                            ),
                                            Expanded(
                                              child: Container(
                                                alignment: Alignment.topRight,
                                                child: FixedSizeText(
                                                    "${data.distance} km   "),
                                              ),
                                            )
                                          ],
                                        ),
                                        Row(
                                          children: <Widget>[
                                            Expanded(
                                              child: Container(
                                                child: FixedSizeText(
                                                  "跑腿费",
                                                  style: TextStyle(
                                                      color: Colors.black45),
                                                ),
                                              ),
                                            ),
                                            Expanded(
                                              child: Container(
                                                alignment: Alignment.topRight,
                                                child: FixedSizeText(
                                                    "${StringUtils.formatNum(data.money * 0.8, 2)} \$   "),
                                              ),
                                            )
                                          ],
                                        ),
                                      ],
                                    ),
                                    flex: 8,
                                  ),
                                ],
                              ),
                            ),
                          ],
                        )),
                    infos.length != 0
                        ? getColumn("运送信息",
                            child: Column(
                              children: <Widget>[
                                Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: Container(
                                        child: FixedSizeText(
                                          "接单时间",
                                          style: TextStyle(
                                              color: Colors.black45),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      child: Container(
                                        alignment: Alignment.topRight,
                                        child: FixedSizeText(
                                            "${infos[0].createTime}"),
                                      ),
                                    )
                                  ],
                                ),
                                ImageView(context,0,imgPath: _imgPath,imgs: imgs,click1: _takePhoto,click2: _openGallery),
                                infos.length>=2? Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: Container(
                                        child: FixedSizeText(
                                          "取件时间",
                                          style: TextStyle(
                                              color: Colors.black45),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      child: Container(
                                        alignment: Alignment.topRight,
                                        child: FixedSizeText(
                                            "${infos[1].createTime}"),
                                      ),
                                    )
                                  ],
                                ):Container(),
                                infos.length>=3? Row(
                                  children: <Widget>[
                                    Expanded(
                                      child: Container(
                                        child: FixedSizeText(
                                          "送达时间",
                                          style: TextStyle(
                                              color: Colors.black45),
                                        ),
                                      ),
                                    ),
                                    Expanded(
                                      child: Container(
                                        alignment: Alignment.topRight,
                                        child: FixedSizeText(
                                            "${infos[2].createTime}"),
                                      ),
                                    )
                                  ],
                                ):Container(),
                                infos.length>=2? ImageView(context,1,imgPath: _imgPath,imgs: imgs,click1: _takePhoto,click2: _openGallery):Container(),
                              ],
                            ))
                        : Container(),
                    getColumn(
                      "备注信息",
                      child: Column(
                        children: <Widget>[
                          Container(
                            child: FixedSizeText(data.remark ?? ""),
                          ),
                          getBtn(infos.length)
                        ],
                      ),
                    ),
                  ],
                ),
              )),
        ],
      ),
    );
  }

  Widget getBtn(int len) {
    switch (len) {
      case 0:
        return Container(
          padding: EdgeInsets.only(top: 10, bottom: 10),
          margin: EdgeInsets.only(left: 50, right: 50),
          child: RaisedButton(
            //提交按钮
            color: Colors.lightBlueAccent,
            highlightColor: Colors.blueAccent,
            splashColor: Colors.blue,
            colorBrightness: Brightness.dark,
            shape:
                RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
            onPressed: () async {
              // POLI
              showDialog<Null>(
                context: context, //BuildContext对象
                barrierDismissible: false,
                builder: (BuildContext context) {
                  return LoadingDialog(
                    //调用对话框
                    text: 'Loading...',
                  );
                },
              );
              String UID = await SPUtils.get("UID");
              String name = await SPUtils.get("phone");
              OrderInfo info = OrderInfo();
              info.oid = data.uuid;
              info.status = 0;
              info.lat = nowPosition.latitude.toString();
              info.lng = nowPosition.longitude.toString();
              orderData o = orderData();
              o.uuid = data.uuid;
              o.status = "0";
              print(UID);
              o.riderId = int.parse(UID);
              o.riderName = name;
              await DioUtils.orderUpdateRider(o, json.encode(info.toJson()))
                  .then((result) {
                if (result.code == 0) {
                  Get.back();
                  Toast.toast(context, msg: "接单成功");
                  // 关闭接单
                  MsgUtils.colseChannel();
                  Get.to(RiderOrderInfo(uuid: data.uuid));
                } else {
                  Get.back();
                  Toast.toast(context,
                      bgColor: Colors.redAccent, msg: result.msg);
                }
              });
              print("点击了接单");
            },
            child: FixedSizeText(
              '立即接单',
              style: TextStyle(color: Colors.white, fontSize: 15),
            ),
          ),
        );
      case 1:
        return Container(
            padding: EdgeInsets.only(top: 10, bottom: 10),
            margin: EdgeInsets.only(left: 50, right: 50),
            child: RaisedButton(
                //提交按钮
                color: Colors.lightBlueAccent,
                highlightColor: Colors.blueAccent,
                splashColor: Colors.blue,
                colorBrightness: Brightness.dark,
                child: FixedSizeText("我已到达取件点"),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10)),
                onPressed: () async {
                  if(_imgPath==null){
                    Toast.toast(context,msg: "请先对商品完成拍照",bgColor: Colors.redAccent);
                    return false;
                  }
                  OrderImg img = OrderImg();
                  img.oid = data.uuid;
                  img.imgType = "0";
                  UploadImg(context,imgPath: _imgPath,img: img);
                  // POLI
                  showDialog<Null>(
                    context: context, //BuildContext对象
                    barrierDismissible: false,
                    builder: (BuildContext context) {
                      return LoadingDialog(
                        //调用对话框
                        text: 'Loading...',
                      );
                    },
                  );
                  String UID = await SPUtils.get("UID");
                  String name = await SPUtils.get("phone");
                  OrderInfo info = OrderInfo();
                  info.oid = data.uuid;
                  info.status = 1;
                  info.lat = nowPosition.latitude.toString();
                  info.lng = nowPosition.longitude.toString();
                  orderData o = orderData();
                  o.uuid = data.uuid;
                  o.status = "0";
                  print(UID);
                  o.riderId = int.parse(UID);
                  o.riderName = name;
                  await DioUtils.orderUpdateRider(o, json.encode(info.toJson()))
                      .then((result) {
                    if (result.code == 0) {
                      Get.back();
                      Toast.toast(context, msg: "取件成功");
                      // 关闭接单
                      MsgUtils.colseChannel();
                      Get.to(RiderOrderInfo(uuid: data.uuid));
                    } else {
                      Get.back();
                      Toast.toast(context,
                          bgColor: Colors.redAccent, msg: result.msg);
                    }
                  });
                  print("点击了取件");
//                  Get.to(UploadImg());
                }));
      case 2:
        return Container(
            padding: EdgeInsets.only(top: 10, bottom: 10),
            margin: EdgeInsets.only(left: 50, right: 50),
            child: RaisedButton(
              //提交按钮
                color: Colors.lightBlueAccent,
                highlightColor: Colors.blueAccent,
                splashColor: Colors.blue,
                colorBrightness: Brightness.dark,
                child: FixedSizeText("已到达送达点"),
                shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(10)),
                onPressed: () async {
                  if(_imgPath==null){
                    Toast.toast(context,msg: "请先对商品完成拍照",bgColor: Colors.redAccent);
                    return false;
                  }
                  OrderImg img = OrderImg();
                  img.oid = data.uuid;
                  img.imgType = "1";
                  UploadImg(context,imgPath: _imgPath,img: img);
                  // POLI
//                  showDialog<Null>(
//                    context: context, //BuildContext对象
//                    barrierDismissible: false,
//                    builder: (BuildContext context) {
//                      return LoadingDialog(
//                        //调用对话框
//                        text: 'Loading...',
//                      );
//                    },
//                  );
                  String UID = await SPUtils.get("UID");
                  String name = await SPUtils.get("phone");
                  OrderInfo info = OrderInfo();
                  info.oid = data.uuid;
                  info.status = 2;
                  info.lat = nowPosition.latitude.toString();
                  info.lng = nowPosition.longitude.toString();
                  orderData o = orderData();
                  o.uuid = data.uuid;
                  o.status = "1";
                  print(UID);
                  o.riderId = int.parse(UID);
                  o.riderName = name;
                  await DioUtils.orderUpdateRider(o, json.encode(info.toJson()))
                      .then((result) {
                    if (result.code == 0) {
                      Get.back();
                      Toast.toast(context, msg: "订单完成");
                      // 关闭接单
                      MsgUtils.colseChannel();
                      Get.to(RiderOrderInfo(uuid: data.uuid));
                    } else {
                      Get.back();
                      Toast.toast(context,
                          bgColor: Colors.redAccent, msg: result.msg);
                    }
                  });
                  print("点击了送达");
//                  Get.to(UploadImg());
                }));
      case 3:
        return Container();
    }
  }

  String getStatus(String status) {
    switch (status) {
      case "0":
        return "进行中";
      case "1":
        return "已完成";
      case "2":
        return "未付款";
      case "3":
        return "待接单";
    }
  }

/*拍照*/
  _takePhoto() async {
    var image = await ImagePicker.pickImage(source: ImageSource.camera);
    OrderImg img = OrderImg();

//    int code = await UploadImg(context,imgPath: image,img: img);
    setState(() {
      _imgPath = image;
    });
  }

/*相册*/
  _openGallery() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
//    OrderImg img = OrderImg();
//    img.oid = data.uuid;
//    img.imgType = "0";
//    int code = await UploadImg(context,imgPath: image,img: img);
    setState(() {
      _imgPath = image;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BaseViewBar(
        childView: BaseTitleBar("订单详情"),
        preferredSize: Size.fromHeight(50.0),
      ),
      body: getBody(),
    );
  }

  @override
  void initState() {
    this.uuid = widget.uuid;
    // TODO: implement initState
    super.initState();
    getData();
  }

  Future<void> getData() async {
    await DioUtils.orderInfo(uuid).then((Map result) async {
      if (result['code'] == 0) {
        data = orderData.fromJson(result['data']);
        if (data.status == "0") {
          await DioUtils.orderInfoList(data.uuid).then((val) {
            if (val.code == 0) {
              json.decode(val.data)['infos'].forEach((v) {
                infos.add(OrderInfo.fromJson(v));
              });
              json.decode(val.data)['imgs'].forEach((v) {
                imgs.add(OrderImg.fromJson(v));
              });
            } else {
              print("获取进行中订单出错:${val.msg}");
            }
            buildLine();
            setState(() {
              isNetworkNotBad = true;
            });
          });
        } else {
          buildLine();
          setState(() {
            isNetworkNotBad = true;
          });
        }

        //图标
//        final Uint8List markerIcon =
//            await getBytesFromAsset('asset/map/begin.png', 150);
//        final Uint8List endIcon =
//            await getBytesFromAsset('asset/map/end.png', 150);
        // 标记起送地点

      }
    });
  }

  // 构建路线导航
  void buildLine() async {
    // 获取当前坐标
    nowPosition = await Geolocator()
        .getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
    // 请求路线坐标
    List<LatLng> _coordinates;

    if (data.status == "0") {
      LatLng begin;
      LatLng end;
      switch (infos.length) {
        case 1:
          // 赶往起送点
          begin = LatLng(nowPosition.latitude, nowPosition.longitude);
          end =
              LatLng(double.parse(data.beginLat), double.parse(data.beginLng));
          _coordinates = await getCoordinates(begin: begin, end: end);
          break;
        case 2:
          // 赶往送达点
          begin = LatLng(nowPosition.latitude, nowPosition.longitude);
          end = LatLng(double.parse(data.endLat), double.parse(data.endLng));
          _coordinates = await getCoordinates(begin: begin, end: end);
          break;
      }
    } else {
      _coordinates = await getCoordinates(
          begin:
              LatLng(double.parse(data.beginLat), double.parse(data.beginLng)),
          end: LatLng(double.parse(data.endLat), double.parse(data.endLng)));
    }

    Markers.add(Marker(
        markerId: MarkerId("begin"),
        infoWindow: InfoWindow(
          title: "起送地点",
        ),
//            icon: BitmapDescriptor.fromBytes(markerIcon),
        position:
            LatLng(double.parse(data.beginLat), double.parse(data.beginLng))));
    Markers.add(Marker(
        markerId: MarkerId("my"),
        infoWindow: InfoWindow(
          title: "我的位置",
        ),
//            icon: BitmapDescriptor.fromBytes(endIcon),
        icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueGreen),
        position: LatLng(nowPosition.latitude, nowPosition.longitude)));
    // 标记送达地点
    Markers.add(Marker(
        markerId: MarkerId("end"),
        infoWindow: InfoWindow(
          title: "送达地点",
        ),
//            icon: BitmapDescriptor.fromBytes(endIcon),
        position:
            LatLng(double.parse(data.endLat), double.parse(data.endLng))));
    _addPolyline(_coordinates);
  }

  Future<List<LatLng>> getCoordinates({LatLng begin, LatLng end}) async {
    List<LatLng> _coordinates =
        await googleMapPolyline.getCoordinatesWithLocation(
            origin: begin, destination: end, mode: RouteMode.driving);
    return _coordinates;
  }

  int _polylineCount = 1;
  List<List<PatternItem>> patterns = <List<PatternItem>>[
    <PatternItem>[], //line
    <PatternItem>[PatternItem.dash(30.0), PatternItem.gap(20.0)], //dash
    <PatternItem>[PatternItem.dot, PatternItem.gap(10.0)], //dot
    <PatternItem>[
      //dash-dot
      PatternItem.dash(30.0),
      PatternItem.gap(20.0),
      PatternItem.dot,
      PatternItem.gap(20.0)
    ],
  ];
  Map<PolylineId, Polyline> _polylines = <PolylineId, Polyline>{};

  _addPolyline(List<LatLng> _coordinates) {
    PolylineId id = PolylineId("poly$_polylineCount");
    Polyline polyline = Polyline(
        polylineId: id,
        patterns: patterns[0],
        color: Colors.blueAccent,
        points: _coordinates,
        width: 10,
        onTap: () {});

    setState(() {
      _polylines[id] = polyline;
      _polylineCount++;
    });
  }

// 获取图标 base64
  Future<Uint8List> getBytesFromAsset(String path, int width) async {
    ByteData data = await rootBundle.load(path);
    ui.Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List(),
        targetWidth: width);
    ui.FrameInfo fi = await codec.getNextFrame();
    return (await fi.image.toByteData(format: ui.ImageByteFormat.png))
        .buffer
        .asUint8List();
  }

  //    infos.length == 1?"货物运送拍照  ${_imgPath != null? '已拍照':'未拍照'}":"货物运送拍照  ${imgs.forEach()}",

}
